#include "mainwindow.h"
#include "writer.h"
#include "reader.h"
#include "shelf.h"
#include "statuswidget.h"

#include <QThreadPool>
#include <QTest>
#include <QVBoxLayout>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    int readTime = QCoreApplication::arguments().at(1).toInt();
    int writeTime = QCoreApplication::arguments().at(2).toInt();
    int shelfSize = QCoreApplication::arguments().at(3).toInt();
    int readersCount = QCoreApplication::arguments().at(4).toInt();
    int writersCount = QCoreApplication::arguments().at(5).toInt();

    StatusWidget* widget = new StatusWidget(shelfSize, readersCount + writersCount, this);
    setCentralWidget(widget);
    show();

    Shelf* shelf = new Shelf(shelfSize);
    connect(shelf, SIGNAL(wrotedBook()), widget, SLOT(incBook()));
    connect(shelf, SIGNAL(waitForEdit()), widget, SLOT(incWaiting()));
    connect(shelf, SIGNAL(doneEdit()), widget, SLOT(decWaiting()));

    QThreadPool* pool = QThreadPool::globalInstance();
    pool->setMaxThreadCount(readersCount + writersCount);

    for (int i = 0; i < writersCount; ++i) {
        Writer* writer = new Writer(*shelf, writeTime, this);
        pool->start(writer);
        // For more randomness
        QTest::qSleep(100);
    }    

    for (int i = 0; i < readersCount; ++i) {
        pool->start(new Reader(*shelf, readTime));
        // For more randomness
        QTest::qSleep(100);
    }
}


